package tree;

/**
 * 654. 最大二叉树
 * 凡是构造二叉树，就是用前序遍历：中左右
 *
 * @author Api
 * @date 2023/10/24 22:54
 */
public class Code654_MaximumBinaryTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return constructMaximumBinaryTree1(nums, 0, nums.length);
    }

    public TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex) {
        // 终止条件
        if (rightIndex - leftIndex < 1) { // 没有元素了
            return null;
        }
        if (rightIndex - leftIndex == 1) { // 只有一个元素了
            return new TreeNode(nums[leftIndex]);
        }
        // 找到当前数组中的最大值和最大值的下标
        int maxIndex = leftIndex; // 最大值所在位置
        int maxValue = nums[maxIndex]; // 最大值
        for (int i = leftIndex + 1; i < rightIndex; i++) {
            if (nums[i] > maxValue) {
                maxValue = nums[i];
                maxIndex = i;
            }
        }
        TreeNode root = new TreeNode(maxValue);
        // 根据maxIndex划分左右子树
        // 左子树
        root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex);
        // 右子树
        root.right = constructMaximumBinaryTree1(nums, maxIndex + 1, rightIndex);
        return root;
    }

}
